package com.example;

import org.I0Itec.zkclient.ZkClient;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


public class Startup {
    private static Connection connection;
    private static Startup instance = null;

    public static Startup getInstance() {
        if (null == instance) {
            synchronized (ConnectionCfg.class) {
                if (null == instance) {
                    return new Startup();
                }
            }
        }
        return instance;
    }

    private Startup() {

    }

    public static void init() throws IOException, SQLException, ClassNotFoundException {
        ZkClient zkClient = new ZkClient("linux121:2181,linux122:2181,linux123:2181");
        String cfg = zkClient.readData("/mysqlCfg", true);
        System.out.println("获得数据库连接池配置信息成功！！");
        System.out.println(cfg);
        Properties pro = new Properties();
        Utils.loadDataToCfg(pro, cfg);
        // 根据zk获得的参数创建数据库连接
        connection = Utils.createDbPoolConnection();
        System.out.println("数据库连接创建成功！！！");
        // 监听节点数据的变化
        Listener.monitor();
        System.out.println("zk监听成功！！！");

    }

    public static Connection getConnection() throws Exception {
        if (connection != null) {
            return connection;
        } else {
            throw new Exception("连接未创建");
        }
    }

    public static void setConnection(Connection connection) {
        Startup.connection = connection;
    }

}